/*
 * Copyright 1994, Black Adder Research, Inc.  This source code may be
 * redistributed and modified with one restriction - do not claim that 
 * you wrote it.
 *
 * Black Adder Research, Inc.
 * 730 Norell Ave. North
 * Stillwater, MN  55082
 * 
 */


#import "Controller.h"
#import "MPEGView.h"
#import <appkit/appkit.h>

@implementation MPEGView : View

- initSize: (const NXSize *) aSize
{
    NXRect imageRect;
	id retVal = nil;

	NXSetRect(&imageRect, 0.0, 0.0, aSize->width, aSize->height);
    [super initFrame:&imageRect];
	strcpy(mpgFile, "");
	if((theData = (unsigned char *)malloc(3 * (int) (aSize->width * aSize->height))) != NULL) {
		if((theBitmap = [[NXBitmapImageRep alloc] initData:theData
			pixelsWide: (int) aSize->width
			pixelsHigh: (int) aSize->height
			bitsPerSample: 8
			samplesPerPixel:3
			hasAlpha:NO
			isPlanar:NO
			colorSpace: NX_RGBColorSpace
			bytesPerRow:0
			bitsPerPixel:0]) != nil) {
	
				retVal = self;
		}
	}
    return(retVal);
}


- runFromFile: (char *) mpegFile
{
	strcpy(mpgFile, mpegFile);
	[self runAgain];
	return(self);
}


- runAgain
{
	char command[256];
	int numPix, numFrPix;
	BOOL shouldLoop = YES;
	FILE *ifp;

	if (strcmp(mpgFile, "") != 0) {
		numPix = 3 * [theBitmap pixelsWide] * [theBitmap pixelsHigh];
		numFrPix = numPix + 3 * sizeof(int); /* for frame number, width, and height */
		sprintf(command, "%s/mpegDecode %s", [[NXBundle mainBundle] directory], mpgFile);
		if ((ifp = popen(command, "r")) != NULL) {
			[self lockFocus];
			while(shouldLoop) {
				if(NXUserAborted()) {
					NXResetUserAbort();
					if(NX_ALERTDEFAULT == NXRunAlertPanel("MPEGStream", 
							"Stop Playback?", "Yes", "No", NULL) ) {
						shouldLoop = NO;
						break;
					}
				}
				fread(theData, 1, 3*sizeof(int), ifp); /* skip frame #, width, height */
				if(fread(theData, 1, numPix, ifp) != numPix) {
					shouldLoop = NO;
					break;
				}
				else {
					[theBitmap draw];
					NXPing();
				}
			}
			[self unlockFocus];
			pclose(ifp);
		}
	}
	return(self);
}


- drawSelf:(const NXRect *)rects :(int)rectCount
{
    [theBitmap draw];
    return self;
}


- free
{
	free(theData);
	[theBitmap free];
    return [super free];
}

@end
